/**
 * @author : wangbo
 * @date : 2020-11-01 18:28
 **/
package com.ohaku.processor;

import com.ohaku.anno.DefaultValue;
import com.ohaku.service.DragonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

import java.util.stream.Stream;

public class DefaultValueByDragonPostProcess implements SmartInitializingSingleton, BeanFactoryPostProcessor {
    BeanFactory beanFactory;


    private static final Logger logger = LoggerFactory.getLogger(DefaultValueByDragonPostProcess.class);


    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;

    }

    @Override
    public void afterSingletonsInstantiated() {
        logger.info("process afterSingletons...");


        // 处理@MyValue注解
        DragonService dragon = beanFactory.getBean(DragonService.class);
        Stream.of(DragonService.class.getDeclaredFields())
                .filter(field -> field.getAnnotation(DefaultValue.class) != null)
                .forEach(field -> {
                    DefaultValue defaultValue = field.getAnnotation(DefaultValue.class);
                    try {
                        field.setAccessible(true);
                        field.set(dragon, defaultValue.value());
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }

                    logger.info("dragon name = " + field.getName());
                    logger.info("dragon value = " + defaultValue.value());


                    /*
                    //反射set

                    String fieldName = field.getName();
                    Class<?> type = field.getType();
                    String setMethodName = "set".concat(fieldName.substring(0, 1).
                            toUpperCase()).concat(fieldName.substring(1));
                    DefaultValue defaultValue = field.getAnnotation(DefaultValue.class);
                    try {
                        Method method = DragonService.class.getMethod(setMethodName, type);
                        method.invoke(dragon, defaultValue.value());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }*/

                });


    }

}